package com.cjkj.system.controller;

import com.alibaba.fastjson2.JSON;
import com.cjkj.common.core.constant.EquipmentConstants;
import com.cjkj.common.core.constant.UserConstants;
import com.cjkj.common.core.domain.R;
import com.cjkj.common.core.utils.StringUtils;
import com.cjkj.common.core.web.controller.BaseController;
import com.cjkj.common.core.web.domain.AjaxResult;
import com.cjkj.common.core.web.page.TableDataInfo;
import com.cjkj.common.log.annotation.Log;
import com.cjkj.common.log.enums.BusinessType;
import com.cjkj.common.security.annotation.InnerAuth;
import com.cjkj.common.security.annotation.RequiresPermissions;
import com.cjkj.common.security.utils.SecurityUtils;
import com.cjkj.system.api.domain.THospitalUser;
import com.cjkj.system.api.model.LoginUser;
import com.cjkj.system.domain.dto.HospitalUserReq;
import com.cjkj.system.domain.dto.UserResetPassword;
import com.cjkj.system.domain.vo.HospitalUserVo;
import com.cjkj.system.service.ITHospitalUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/user")
public class HospitalUserController extends BaseController
{
    @Resource
    private ITHospitalUserService userService;

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username)
    {
        THospitalUser hospitalUser = userService.getUserByUserName(username);
        if (StringUtils.isNull(hospitalUser))
        {
            return R.fail("用户名或密码错误！");
        }
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(hospitalUser);
        sysUserVo.setHospitalId(hospitalUser.getHospitalId());
        sysUserVo.setDeptId(hospitalUser.getDeptId());
        if(UserConstants.USER_TYPE_HOSPITAL.equals(hospitalUser.getUserType())) {
            sysUserVo.setRoles(UserConstants.HOSPITAL_ROLES);
            sysUserVo.setPermissions(UserConstants.HOSPITAL_PERMISSIONS);
        }
        if(UserConstants.USER_TYPE_DOCTOR.equals(hospitalUser.getUserType())) {
            sysUserVo.setRoles(UserConstants.DOCTOR_ROLES);
            sysUserVo.setPermissions(UserConstants.DOCTOR_PERMISSIONS);
        }

        return R.ok(sysUserVo);
    }
    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        THospitalUser user = userService.selectTHospitalUserByUserId(SecurityUtils.getUserId());

        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        if(UserConstants.USER_TYPE_HOSPITAL.equals(user.getUserType())) {
            ajax.put("roles", UserConstants.HOSPITAL_ROLES);
            ajax.put("permissions", UserConstants.HOSPITAL_PERMISSIONS);
        }
        if(UserConstants.USER_TYPE_DOCTOR.equals(user.getUserType())) {
            ajax.put("roles", UserConstants.DOCTOR_ROLES);
            ajax.put("permissions", UserConstants.DOCTOR_PERMISSIONS);
        }
        return ajax;
    }
    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters(String type)
    {
        THospitalUser user = userService.selectTHospitalUserByUserId(SecurityUtils.getUserId());
        if(UserConstants.USER_TYPE_HOSPITAL.equals(user.getUserType())) {
            if (EquipmentConstants.EQUIPMENT_TYPE_MONITOR_PAD_TYPE.equals(type)) {
                return AjaxResult.success(JSON.parse(UserConstants.TJ01_HOSPITAL_ROUTERS));
            }
            if(EquipmentConstants.EQUIPMENT_TYPE_SMART_BRACELET_TYPE.equals(type)) {
                return AjaxResult.success(JSON.parse(UserConstants.TJ02_HOSPITAL_ROUTERS));
            }
            if (EquipmentConstants.EQUIPMENT_TYPE_EB_TYPE.equals(type)) {
                return AjaxResult.success(JSON.parse(UserConstants.TJ03_HOSPITAL_ROUTERS));
            }
        }

        if(UserConstants.USER_TYPE_DOCTOR.equals(user.getUserType())) {
            if (EquipmentConstants.EQUIPMENT_TYPE_MONITOR_PAD_TYPE.equals(type)) {
                return AjaxResult.success(JSON.parse(UserConstants.TJ01_DOCTOR_ROUTERS));
            }
            if(EquipmentConstants.EQUIPMENT_TYPE_SMART_BRACELET_TYPE.equals(type)) {
                return AjaxResult.success(JSON.parse(UserConstants.TJ02_DOCTOR_ROUTERS));
            }
            if (EquipmentConstants.EQUIPMENT_TYPE_EB_TYPE.equals(type)) {
                return AjaxResult.success(JSON.parse(UserConstants.TJ03_DOCTOR_ROUTERS));
            }
        }
        return AjaxResult.error();
    }

    /**
     * 重置密码
     * @param user
     * @return
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPassword(@Valid @RequestBody UserResetPassword user)
    {
        String newPassword = SecurityUtils.encryptPassword(user.getPassword());
        return success(userService.resetUserPwd(user.getUserName(), newPassword));
    }

    /**
     * 获取用户列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(HospitalUserReq req)
    {
        startPage();
        req.setHospitalId(SecurityUtils.getLoginUser().getSysUser().getHospitalId());
        List<HospitalUserVo> list = userService.selectTHospitalUserList(req);
        return getDataTable(list);
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody THospitalUser user)
    {
        user.setHospitalId(SecurityUtils.getLoginUser().getSysUser().getHospitalId());
        user.setUserType(UserConstants.USER_TYPE_DOCTOR);
        return toAjax(userService.add(user));
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userId}")
    public AjaxResult remove(@PathVariable("userId") String userId)
    {
        if (SecurityUtils.getUserId().equals(userId))
        {
            return AjaxResult.error("当前用户不能删除！");
        }
        return toAjax(userService.deleteUserById(userId));
    }

    /**
     * 查询用户详情
     * @param userId
     * @return
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") String userId)
    {
        return success(userService.selectTHospitalUserByUserId(userId));
    }

    /**
     * 修改用户
     * @param tHospitalUser
     * @return
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody THospitalUser tHospitalUser)
    {
        tHospitalUser.setPassword(null);
        return toAjax(userService.updateTHospitalUser(tHospitalUser));
    }

    /**
     * 根据部门ID获取医生列表
     */
    @GetMapping("/doctorTree")
    public AjaxResult doctorTree(String deptId){
        String hospitalId = SecurityUtils.getLoginUser().getSysUser().getHospitalId();
        return AjaxResult.success(userService.getUserByDept(hospitalId, deptId));
    }

    /**
     * 验证密码是否为初始密码
     */
    @GetMapping("/verifyPwd")
    public AjaxResult verifyPwd() {
        String userId = SecurityUtils.getUserId();
        return AjaxResult.success(userService.verifyUserPassword(userId));
    }
}
